<?php
/**
 * +----------------------------------------------------------------------
 * | 用户中心控制器
 * +----------------------------------------------------------------------
 *                      .::::.
 *                    .::::::::.            | AUTHOR: siyu
 *                    :::::::::::           | EMAIL: 407593529@qq.com
 *                 ..:::::::::::'           | QQ: 407593529
 *             '::::::::::::'               | WECHAT: zhaoyingjie4125
 *                .::::::::::               | DATETIME: 2019/07/19
 *           '::::::::::::::..
 *                ..::::::::::::.
 *              ``::::::::::::::::
 *               ::::``:::::::::'        .:::.
 *              ::::'   ':::::'       .::::::::.
 *            .::::'      ::::     .:::::::'::::.
 *           .:::'       :::::  .:::::::::' ':::::.
 *          .::'        :::::.:::::::::'      ':::::.
 *         .::'         ::::::::::::::'         ``::::.
 *     ...:::           ::::::::::::'              ``::.
 *   ```` ':.          ':::::::::'                  ::::..
 *                      '.:::::'                    ':'````..
 * +----------------------------------------------------------------------
 */
namespace app\api\controller;


use app\api\service\JwtAuth;
use app\common\model\Users;
use think\facade\Db;
use think\facade\Request;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\model\Trademark;
use app\common\model\Copyright;


class Index extends Base
{
    public function index(){
        echo 111;
    }

    public function getindexcatgory(){
        $datalist = Db::name('cateindex')->where('status',1)->field('id,title,sub_title,pic,color')->select()->toArray();
        foreach ($datalist as &$value) {
          $value['list'] = Db::name('projects')->where('status',1)->where('pid',$value['id'])->field('id,title,pic')->select();
        }
        $this->result(['datalist' => $datalist], 1, 'success');
    }

    public function getindexcatgoryitem(){
        $catid = request()->get('id/d');
        $data = Db::name('cateindex')->where('status',1)->where('id',$catid)->field('id,title,sub_title,pic,color')->find();
        $data['list'] = Db::name('projects')->where('status',1)->where('pid',$data['id'])->field('id,title,pic')->select();
        $this->result(['data' => $data], 1, 'success');
    }

    public function getprojectdetail(){
        $id = request()->get('id/d');
        $data = Db::name('projects')->where('status',1)->where('id',$id)->field('id,title,pic')->find();
        $data['sku'] = Db::name('projects_sku')->where('status',1)->where('projects_id',$data['id'])->field('id,specs_value_id,price')->select();
        $arr = array_unique(explode(',', implode(',',array_column($data['sku']->toArray(), 'specs_value_id'))));

        foreach ($arr as $item) {
            $specs_value = Db::name('specs_value')->where('id',$item)->find();
            $arr_specs_value = Db::name('specs_value')->where('specs_id',$specs_value['specs_id'])->field('id')->select();
            foreach ($arr_specs_value as $value) {
                if(in_array($value['id'],$arr) && $value['id'] !== $item  ){
                  $arr_list[$specs_value['specs_id']][] = $specs_value;
                }
            }
        }

        foreach($arr_list as &$val1){
            if(count($val1) < 2){

            }else{
               $val1 = $this->array_unique_fb($val1,array('id'));
            }
            
        }

        $spece = config('spece');
        
        foreach ($spece as &$specevalue) {
          foreach ($arr_list as $arritem) {
            foreach ($arritem as  $_arritem) {
                if($specevalue['id'] == $_arritem['specs_id']){
                  $specevalue['sku'][] = $_arritem;
                }
            }
            
         }
            
        }
         

        $this->result(['data' => $data,'spece'=>$spece], 1, 'success');
    }

    public function array_unique_fb($arr=array(),$filter){   
        $res = array();      
        foreach ($arr as $key => $value) {
            $newkey='';
            if (is_array($filter)) {
                foreach ($filter as $fv) {
                    $newkey.=$value[$fv];
                }
            }else{
                $newkey=$value[$filter];
            }
            foreach ($value as $vk => $va) {
                if (isset($res[$newkey])) {
                    $res[$newkey][$vk]=$va;
                }else{
                    $res[$newkey][$vk]=$va;
                }
            }
        }
        return $res;
    }

    public function getsiteinfo(){
       $data = Db::name('system')->field('title,key,des,icp,logo,copyright,address,contacts,tel,mobile_phone,fax,email,qrcode')->find(1);
       $this->result(['data' => $data], 1, 'success');
    }

    public function getarticle(){
      $datalist = Db::name('article')->where('status',1)->field('id,title,create_time')->order('sort asc')->limit(5)->select();
      $this->result(['datalist' => $datalist], 1, 'success');
    }

    public function getallarticle(){
      $datalist = Db::name('article')->where('status',1)->field('id,title,create_time')->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 15]);
      $this->result(['datalist' => $datalist], 1, 'success');
    }

    public function getarticledetail(){
      $id = request()->get('id/d');
      $data = Db::name('article')->where('id',$id)->find();
      if($data){
          $this->result(['data' => $data], 1, 'success');
      }else{
          $this->result([], 0, '非法请求');
      }
      
    }

    public function getaboutinfo(){
      $data = Db::name('debris')->where('id',1)->find();
      $this->result(['data' => $data], 1, 'success');
    }

    public function getlink(){
      $data = Db::name('link')->where('status',1)->field('name,logo,url')->select()->toArray();
      $this->result(['data' => $data], 1, 'success');
    }

    public function brandlist(){
        $list = Db::name('brand')->field('id,title')->where('status', 1)->order('sort asc')->select();
        $this->result(['list'=>$list], 1, '');
    }

    public function getTrademarkList(){
       $data = Request::get();
       $where = [];
        isset($data['brand_id']) && $data['brand_id'] !== '0'  ? $where[] = array('brand_id','=',$data['brand_id']) : '';
        isset($data['type']) && $data['type'] !== '0' ?  $where[] = array('type','=',$data['type']) : '';
        if(isset($data['wordnum']) && $data['wordnum'] !== '0'){
          if($data['wordnum'] >= 6 ){
              $where[] = array('wordnum','>=',6);
          }else{
              $where[] = array('wordnum','=',$data['wordnum']);
          }
          
        }
        isset($data['title']) && $data['title'] !== '' ?  $where[] = array('title','like','%'.$data['title'].'%') : '';

       if(isset($data['price']) && $data['price'] !== '0'){
          $arrprice = explode(',', $data['price']);
          if($arrprice[1] == ''){
            $where[] = array('price','>',$arrprice[0]);
            $datalist = Trademark::where('status',1)->where($where)->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 12]);
          }else{
            $where[] = array('price','between',$data['price']);
            $datalist = Trademark::where('status',1)->where($where)->whereBetween('price',$data['price'])->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 12]);
          }
          
       }else{
  
          $datalist = Trademark::where('status',1)->where($where)->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 12]);
       }
       foreach ($datalist as $k => $v) {
            if ($datalist[$k]['brand_id']) {
                $v['brand_id'] = $v->brand->getData('title');
            }
        }
       $this->result(['datalist' => $datalist], 1, 'success');
    }

    //获取版权列表
    public function getBqList(){
       $data = Request::get();
       $where = [];

       isset($data['title']) && $data['title'] !== '' ?  $where[] = array('name','like','%'.$data['title'].'%') : '';

       if(isset($data['price']) && $data['price'] !== '0'){
      
          $arrprice = explode(',', $data['price']);

          if($arrprice[1] == ''){
            $where[] = array('price','>',$arrprice[0]);
            $datalist = Copyright::where('status',1)->where($where)->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 12]);
          }else{
            $where[] = array('price','between',$data['price']);
            $datalist = Copyright::where('status',1)->where($where)->order('sort asc')->fetchSql(true)->paginate(['query'=> Request::get(),'list_rows' => 12]);
          }
          
       }else{
          $datalist = Copyright::where('status',1)->where($where)->order('sort asc')->paginate(['query'=> Request::get(),'list_rows' => 12]);
       }
       $this->result(['datalist' => $datalist], 1, 'success');
    }
    //滚动公告
    public function getrolelist(){
        $data1 = Trademark::where('status',1)->orderRaw('rand()')->field('id,title,saletype,price')->order('update_time desc')->limit(5)->select()->toArray();
        $data2 = Copyright::where('status',1)->orderRaw('rand()')->field('id,name as title,saletype,price')->order('update_time desc')->limit(5)->select()->toArray();

        foreach($data1 as $k => &$v){
           $v['type'] = 0;
          switch ($v['saletype']) {
            case 0:
             $v['saletype'] = '出售中';
              break;
            case 1:
               $v['saletype'] = '议价中';
              break;
            case 2:
               $v['saletype'] = '已售出';
              break;
            default:
              break;
          }
        }

        foreach($data2 as $k => &$vs){
          $vs['type'] = 1;
          switch ($vs['saletype']) {
            case 0:
             $vs['saletype'] = '出售中';
              break;
            case 1:
               $vs['saletype'] = '议价中';
              break;
            case 2:
               $vs['saletype'] = '已售出';
              break;
            default:
              break;
          }
        }

        $datalist = array_merge($data1,$data2);
        $datalist = array_chunk($datalist, 3);

        $this->result(['datalist' => $datalist], 1, 'success');
    }

    public function tojidatong(){
       $data = Db::name('tongji')->find(1);
       $data['year'] = date('Y',time())-1;

       $data['scount'] = $data['zuoyunxian']+$data['xinrongqu']+$data['tianzhengxian']+$data['guanglingxian']+$data['lingqiuxian'] + $data['hunyuanxian'] + $data['yanggaoxian'] + $data['nanjiaoqu'] + $data['datongxian'] + $data['chengqu'];

       $mouthlist = [$data['mouth1'] , $data['mouth3'] ,$data['mouth5'] ,$data['mouth7'] ,$data['mouth9'],$data['mouth11'] ,$data['mouth12']];
          $brandlist['brand'] = Db::name('brand')->column('title');
          $brandlist['tongji'] = Db::name('brand')->column('tongji');

 
      $this->result(['data' => $data,'mouthlist'=>$mouthlist,'brandlist'=>$brandlist], 1, 'success');

    }

    public function getweiquan(){
       $data = Db::name('debris')->field('title,description,image')->find(2);
       $this->result(['data' => $data], 1, 'success');
    }


    public function sendsms()
    {
    	$phone = trim(Request::param("phone"));
      if (!is_mobile_phone($phone)) {
            $this->result([], 0, '手机号码格式不正确！');
      }
    	$data = \app\common\model\Config::where('inc_type', 'sms')->select();
      $config = convert_arr_kv($data, 'name', 'value');

        //生成验证码
        $code = rand(100000,999999);
        $jsoncode = json_encode(array('code'=>$code));

        AlibabaCloud::accessKeyClient($config['accessKeyId'],$config['accessKeySecret'])
                        ->regionId('cn-hangzhou')
                        ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                                  ->product('Dysmsapi')
                                  // ->scheme('https') // https | http
                                  ->version('2017-05-25')
                                  ->action('SendSms')
                                  ->method('POST')
                                  ->host('dysmsapi.aliyuncs.com')
                                  ->options([
                                                'query' => [
                                                  'RegionId' => "cn-hangzhou",
                                                  'PhoneNumbers' => $phone,
                                                  'SignName' => $config['signName'],
                                                  'TemplateCode' => $config['templateCode'],
                                                  'TemplateParam' => $jsoncode,
                                                ],
                                            ])
                                  ->request();
               cache('code_'.$phone, $code, 300);
              $this->result([], 1, '短信发送成功！');
        } catch (ClientException $e) {
            $this->result([], 0, $e->getErrorMessage() . PHP_EOL);
        } catch (ServerException $e) {
            $this->result([], 0, $e->getErrorMessage() . PHP_EOL);
        }

    }

    public function login()
    {
    	$phone = trim(Request::param("phone"));
    	$code = trim(Request::param("code"));
      if (!is_mobile_phone($phone)) {
            $this->result([], 0, '手机号码格式不正确！');
      }
      $cachecode = cache('code_'.$phone);
      if(!$cachecode){
        $this->result([], 0, '验证码已过期，请重新获取');
      }

    	if($cachecode == $code){
        $user = Db::name('users')->where('mobile', '=', $phone)->field('id,mobile,fullname,cname,last_login_time,status,verifystatus,type_id')->find();

        if($user){
          if ($user['status'] == 1) {
            $jwtAuth = JwtAuth::getInstance();
            $token = $jwtAuth->setUid($user['id'])->encode()->getToken();
            Users::where('id', $user['id'])
                    ->update(['last_login_time' => time(), 'last_login_ip' => Request::ip()]);
            $this->result(['token' => $token,'userinfo'=>$user], 1, '登录成功');
          }else{
             $this->result([], 0, '用户已被禁用');
          }
        }else{
          $data = [];
          $data['last_login_time'] = $data['create_time'] = time();
          $data['create_ip']       = $data['last_login_ip'] = Request::ip();
          $data['status']          = 1;
          $data['status']          = 1;
          $data['mobile']          = $phone;
          $data['mobile_validated']  = 1;
          
          $id = Db::name('users')->insertGetId($data);
          if ($id) {
              $jwtAuth = JwtAuth::getInstance();
              $token = $jwtAuth->setUid($id)->encode()->getToken();
              Users::where('id', $user['id'])
                    ->update(['last_login_time' => time(), 'last_login_ip' => Request::ip()]);
              $userinfo = Db::name('users')->where('id', '=', $id)->field('id,mobile,fullname,cname,last_login_time,status,verifystatus,type_id')->find();
              $this->result(['token' => $token,'userinfo'=>$userinfo], 1, '登录成功');
          } else {
              $this->result([], 0, '注册失败');
          }
        }
    	}else{
    		$this->result([], 0, '验证码错误'.cache('code_'.$phone));
    	}
    }

     // 邮件发送
    private function trySend($email,$title,$content){
        //检查是否邮箱格式
        if (!is_email($email)) {
            return ['error' => 1, 'msg' => '邮箱码格式有误'];
        }
        $send = send_email($email, $title,$content);
        if ($send) {
            return ['error' => 0, 'msg' => '邮件发送成功！'];
        } else {
            return ['error' => 1, 'msg' => '邮件发送失败！'];
        }
    }

   
}
